class_name CardVisuals
extends Control

@export var card: Card : set = set_card

@onready var panel: Panel = $Panel
@onready var cost: Label = $Cost
@onready var icon: TextureRect = $Icon
@onready var rarity: TextureRect = $Rarity
@onready var card_repeat_number = $CardRepeatNumber

func set_card(value: Card) -> void:
	if not is_node_ready():
		await ready
	
	card = value
	_update_cost_display()
	if card.card_max_repeat_num == 0:
		card_repeat_number.visible = false
	else:
		card_repeat_number.visible = true	
	card_repeat_number.text = str(card.card_current_repeat_num) + "/" +str(card.card_max_repeat_num)
	icon.texture = card.icon
	
	# 安全设置稀有度颜色，避免访问无效的rarity值
	if card and card.rarity != null and Card.RARITY_COLORS.has(card.rarity):
		rarity.modulate = Card.RARITY_COLORS[card.rarity]
	else:
		# 如果稀有度无效，使用默认颜色
		rarity.modulate = Color.WHITE
		print("警告：卡牌 %s 的稀有度无效，使用默认颜色" % (card.id if card else "未知"))

# 新增：更新费用显示（考虑修改器）
func update_cost_display(targets: Array = []) -> void:
	if not card:
		return
	
	_update_cost_display(targets)

# 内部方法：更新费用显示
func _update_cost_display(targets: Array = []) -> void:
	if not card:
		return
	
	var display_cost = card.cost
	
	# 如果有targets，尝试获取考虑修改器后的实际费用
	if targets.size() > 0:
		# 尝试获取玩家的modifier_handler
		var player = _get_player_from_targets(targets)
		if player and player.get("modifier_handler") != null:
			var cost_modifier = player.modifier_handler.get_modifier(Modifier.Type.CARD_COST)
			if cost_modifier:
				var cost_increase = cost_modifier.get_modified_value(0)
				display_cost += cost_increase
	
	cost.text = str(display_cost)

# 辅助方法：从targets中获取玩家
func _get_player_from_targets(targets: Array) -> Node:
	for target in targets:
		if target is Player:
			return target
		# 如果target不是Player，尝试通过场景树查找
		var tree = target.get_tree()
		if tree:
			var player = tree.get_first_node_in_group("player")
			if player:
				return player
	return null
